package sw6.girafplaceclient;

import sw6.admin.R;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

/**
 * Shows the details for a selected application, in GirafPlace.
 * @author SW6C
 */
public class MainActivity extends ListActivity {
	
	/** Log tag. */
	protected final String tag = "GirafPlaceClient";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setListAdapter(ApplicationAdapter.getInstance(this));
	}
	
	/**
	 * Shows the details for the selected application.
	 * @param l The ListView of the application.
	 * @param v The View of the application.
	 * @param position The position of the application.
	 * @param id The ID of the application.
	 * @exception ActivityNotFoundExeption If no intent is found for the selected application.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		AppView appView = (AppView)v;
		
		final Intent intent = new Intent(MainActivity.this,AppDetailsActivity.class);
		intent.putExtra("APP", appView.getApp());
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Log.e(tag, e.getMessage());
		}
		
		super.onListItemClick(l, v, position, id);
	}
	
	@Override
	protected void onResume() {
		new NetworkTask(this).execute();
		super.onResume();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	/**
	 * Is executed, when a setting in the menu in GirafPlace is selected. 
	 * (E.g: If Refresh is selected, the list of available applications is refreshed.)
	 * @param item The setting selected in the menu.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.refresh:
			new NetworkTask(this).execute();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}